package chat.server.statemachine.identity;

import java.io.IOException;

import chat.State;
import chat.server.ChatServerState;
import chat.statemachine.AbstractContent;
import chat.statemachine.AlgorithmActionInvocationException;

public class AlgorithmIdentityActions {
	public static Object receiveIdentityContent(final State state,
			final AbstractContent content)
	throws AlgorithmActionInvocationException {
		ChatServerState sstate = null;
		if (content == null) {
			throw new IllegalArgumentException(
			"Try executing action with null content");
		}
		if (state == null) {
			throw new IllegalArgumentException(
			"Try executing action with null state");
		}
		if (state instanceof ChatServerState) {
			sstate = (ChatServerState) state;
		} else {
			throw new IllegalArgumentException(
					"Try executing action with state of wrong type ("
					+ state.getClass().getName()
					+ " instead of ChatServerState");
		}
		if (content instanceof IdentityContent) {
			IdentityContent ic = (IdentityContent) content;
			System.out.println("Identity received from " + ic.getIam());
			sstate.neighbors.put(ic.getIam(), sstate.currKey);
		} else {
			throw new AlgorithmActionInvocationException(
					"Error when executing action: not right message type ("
					+ content.getClass().getName() + ")");
		}
		return null;
	}
	public static Object receiveAskIdentityContent(final State state,
			final AbstractContent content)
	throws AlgorithmActionInvocationException {
		ChatServerState sstate = null;
		if (content == null) {
			throw new IllegalArgumentException(
			"Try executing action with null content");
		}
		if (state == null) {
			throw new IllegalArgumentException(
			"Try executing action with null state");
		}
		if (state instanceof ChatServerState) {
			sstate = (ChatServerState) state;
		} else {
			throw new IllegalArgumentException(
					"Try executing action with state of wrong type ("
					+ state.getClass().getName()
					+ " instead of ChatServerState");
		}
		if (content instanceof IdentityAskContent) {
			IdentityAskContent iac = (IdentityAskContent) content;
			
			System.out.println("Ask identity from " + iac.getFrom());
			
			IdentityContent ic = new IdentityContent(sstate.identity,sstate.neighbors.keySet());
			/* Sending my identity, and my list of neighbors */
			try {
				sstate.server.sendToAServer(sstate.currKey, AlgorithmIdentity.IDENTITY_MESSAGE.getActionIndex(), ic);
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else {
			throw new AlgorithmActionInvocationException(
					"Error when executing action: not right message type ("
					+ content.getClass().getName() + ")");
		}
		return null;
	}
}
